#include "appmysqlconfig.h"
#include "CTConfig.h"

#define MAIN_SECTION    "Global"

// int型
#define GETINT(name, value) \
	value = cfg.GetInt(MAIN_SECTION, name, &iRet); \
	if (iRet) \
	{ \
	CT_THROW(("[%s]%s failed %d", MAIN_SECTION, name, iRet)); \
	}

// char数组
#define GETSTR(name, value) \
	s = cfg.GetString(MAIN_SECTION, name, &iRet); \
	if (iRet) \
	{ \
	CT_THROW(("[%s]%s failed %d", MAIN_SECTION, name, iRet)); \
	} \
	iRet = ct_snprintf(CT_STRSIZE(value), "%s", s.c_str()); \
	if (iRet < 0) \
	{ \
	CT_THROW(("[%s]%s too long, over %d", MAIN_SECTION, name, sizeof(value))); \
	}

// string
#define GETSTRING(name, value) \
	value = cfg.GetString(MAIN_SECTION, name, &iRet); \
	if (iRet) \
	{ \
	CT_THROW(("[%s]%s failed %d", MAIN_SECTION, name, iRet)); \
	}

void CAppMysqlConfig::LoadConfig(const char* sConfigFile)
{
	CTConfig cfg;
	string s;
	int iRet = cfg.LoadConfig(sConfigFile);
	if (iRet)
	{
		CT_THROW(("LoadConfig failed: %d", iRet));
	}

	GETSTR("DBHost", DBHost);
	GETSTR("DBUser", DBUser);
	GETSTR("DBPass", DBPass);
	int iPort = 0;
	GETINT("DBPort", iPort);
	DBPort = (unsigned short)(iPort & 0xFFFF);
	GETSTR("DBSocket", DBSocket);

	LoadLogConfig(sConfigFile);
}

void CAppMysqlConfig::LoadLogConfig(const char* sConfigFile)
{
	CTConfig cfg;
	int iRet = cfg.LoadConfig(sConfigFile);
	if (iRet)
	{
		CT_THROW(("LoadConfig failed: %d", iRet));
	}

	int iLogFileNum = 0, iLogFileSize = 0;
	GETINT("LogFileNum", iLogFileNum);
	GETINT("LogFileSize", iLogFileSize);
	CT_NLOG->Init(ENamed, NULL, FILE_NORMALLOG, iLogFileSize, iLogFileNum);
	CT_ELOG->Init(ENamed, NULL, FILE_ERRORLOG, iLogFileSize, iLogFileNum);
	CT_STAT->Init(ENamed, NULL, FILE_STATLOG, iLogFileSize, iLogFileNum);
	CT_STAT->SetFormat(ETime|ENewLine);

	// 设置filter
	string str;
	GETSTRING("LogFormat", str)
		CT_NLOG->SetFormatByStr(str.c_str());
	CT_ELOG->SetFormatByStr(str.c_str());

	// 设置filter
	GETSTRING("LogFilter", str)
		CT_NLOG->SetFilterByStr(str.c_str());
	CT_ELOG->SetFilterByStr(str.c_str());

	CT_INFO(("LogFormat=%d LogFilter=%d", CT_NLOG->GetFormat(), CT_NLOG->GetFilter()));
}


